package com.lemon.security.filter;

import com.lemon.security.properties.JwtConfigProperties;
import com.lemon.security.dto.LoginUserDetail;
import com.lemon.security.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 李猛
 * @datetime 2024/2/15 0:54
 * @description 认证过滤器
 */
@Slf4j
@Component
public class BasicAuthFilter extends OncePerRequestFilter {
    @Resource
    private JwtConfigProperties properties;

    /**
     * 认证时执行过滤器
     *
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //1.获取token
        String token = request.getHeader(properties.getHeader());
        log.info("doFilterInternal.token:{}", token);
        if (StringUtils.hasText(token)) {
            LoginUserDetail loginUserDetail = JwtUtil.getCurrentUser(token);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUserDetail, null, null);
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            //放行
            filterChain.doFilter(request, response);
        } else {
            //放行
            filterChain.doFilter(request, response);
        }
    }
}
